package com.jmb.api.common.utils;

import com.jmb.api.common.constant.RedisConstant;
import com.jmb.api.common.exception.LeaseException;
import com.jmb.api.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;


public class JwtUtil {





    public static String createToken(Integer userId,String username){
        return Jwts.builder().setSubject("jmb-api")
                .setExpiration(new Date(System.currentTimeMillis() + RedisConstant.USER_LOGIN_TOKEN_TTL_SEC*1000L))
                .claim("userId",userId)
                .claim("username",username)
                .signWith(RedisConstant.tokenSignKey)
                .compact();
    }
    public static Claims parseToken(String token){
        if (token == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        try {
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(RedisConstant.tokenSignKey).build();
            return jwtParser.parseClaimsJws(token).getBody();
        }
        catch (ExpiredJwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

}
